package us.codecraft.webmagic.samples.pipeline;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Map;

public class MongodbPipeline implements Pipeline {

    private static MongoCollection<Document> collection=null;
    static {
        //连接到mongoDBJDBC
        MongoClient mongoClient=new MongoClient("localhost",27017);
        //连接到数据库
        MongoDatabase mongoDatabase=mongoClient.getDatabase("soqi");
        System.out.println("Connect to database successfully");
        collection=mongoDatabase.getCollection("clothes");
        if(collection==null)
            mongoDatabase.createCollection("clothes");
        collection=mongoDatabase.getCollection("clothes");
        System.out.println("获取集合clothes成功!");

    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        for(Map.Entry<String,Object> entry:resultItems.getAll().entrySet()){
            Document document=new Document(entry.getKey(),entry.getValue());
            collection.insertOne(document);
        }
    }
}
